package cn.sky1998.mango.framework.utils.ImageUtils;

import cn.sky1998.mango.common.utils.FileUploadUtils;
import cn.sky1998.mango.common.utils.uuid.IdUtils;
import cn.sky1998.mango.framework.config.MangoConfig;
import cn.sky1998.mango.framework.utils.ImageUtils.entity.FontForm;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * 上传一个底图、一个二维码，两段文案
 * @author tcy
 * @Date 20-07-2022
 */
@Component
public class DrawImgUtils {

    @Autowired
    private FileUploadUtils fileUtils;

    @Autowired
    private MangoConfig mangoConfig;

    public static void main(String[] args) throws IOException {
       // String backgroundPath = "https://pic.netbian.com/uploads/allimg/220717/002302-1657988582ec9f.jpg";
       //
       //// getImgInfo(backgroundPath);
       // String qrCodePath = "D:\\idea_demo\\2.jpg";
       // String message01 ="长按识别下方二维码，查看更多劲爆图文和视频";
       // String message02 = "男人必备，你的私房小秘书！";
       // String outPutPath="D:\\idea_demo\\end.jpg";
       //
       // new DrawImgUtils().overlapImage(backgroundPath,qrCodePath,message01,message02);
        //overlapImage(backgroundPath,qrCodePath,message01,message02,outPutPath);
        List<FontForm> list=new ArrayList();
        FontForm fontForm=new FontForm();
        fontForm.setTitle("吴");
        fontForm.setStyle(FontForm.BOLD);
        fontForm.setColor(Color.white);
        fontForm.setSize(90);
        fontForm.setX(150);
        fontForm.setY(320);
        list.add(fontForm);

        FontForm fontForm1=new FontForm();
        fontForm1.setTitle("烦恼全吴");
        fontForm1.setColor(new Color(51, 129, 107));
        fontForm1.setSize(60);
        fontForm1.setX(305);
        fontForm1.setY(420);
        list.add(fontForm1);
        new DrawImgUtils().writeImage("D:\\idea_demo\\mango-web\\底图.png","D:\\idea_demo\\mango-web\\处理后.png",list);

    }

    /**
     *  二维码所处的位置
     * @param backgroundPath 背景图
     * @param qrCodePath 二维码
     * @param message01 文字1
     * @param message02 文字2
     * @param outPutPath 输出图片路径
     * @return
     */
    public static String overlapImage(String backgroundPath,String qrCodePath,String message01,String message02,String outPutPath,
                                      Integer position_x,Integer position_y){
        try {
            //设置图片大小
            //BufferedImage background = resizeImage(1000,618, ImageIO.read(new File(backgroundPath)));
            //原始图片宽度、高度
            Integer sourceWidth=getImgWidth(backgroundPath);
            Integer sourceHeight=getImgHeight(backgroundPath);

            BufferedImage background = resizeImage(sourceWidth,sourceHeight, ImageIO.read(new File(backgroundPath)));
            BufferedImage qrCode = resizeImage(150,150,ImageIO.read(new File(qrCodePath)));

            //二维码位置
            int target_x= (int) (sourceWidth*position_x*0.01);
            int target_y= (int) (sourceHeight*position_y*0.01);

            //在背景图片中添加入需要写入的信息，例如：扫描下方二维码，欢迎大家添加我的淘宝返利机器人，居家必备，省钱购物专属小秘书！
            Graphics2D g = background.createGraphics();
            g.setColor(Color.white);
            g.setFont(new Font("微软雅黑",Font.BOLD,20));
            g.drawString(message01,50 ,target_x);
            //g.drawString(message01,530 ,190);
            //g.drawString(message02,530 ,220);
            //g.drawString(message02,530 ,target_x-150-30);

            //在背景图片上添加二维码图片
           // g.drawImage(qrCode, 700, 240, qrCode.getWidth(), qrCode.getHeight(), null);

            g.drawImage(qrCode, target_x, target_y-100, qrCode.getWidth(), qrCode.getHeight(), null);
            g.dispose();

            //输出图片
            ImageIO.write(background, "jpg", new File(outPutPath));
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     *  二维码所处的位置
     * @param backgroundPath 背景图
     * @param qrCodePath 二维码
     * @param message01 文字1
     * @param message02 文字2
     * @param outPutPath 输出图片路径
     * @return
     */
    public static String overlapImage(String backgroundPath,String qrCodePath,String message01,String message02,String outPutPath){
        try {
            //设置图片大小
            BufferedImage background = resizeImage(1000,618, ImageIO.read(new File(backgroundPath)));
            BufferedImage qrCode = resizeImage(150,150,ImageIO.read(new File(qrCodePath)));

            //在背景图片中添加入需要写入的信息，例如：扫描下方二维码，欢迎大家添加我的淘宝返利机器人，居家必备，省钱购物专属小秘书！
            Graphics2D g = background.createGraphics();
            g.setColor(Color.white);
            g.setFont(new Font("微软雅黑",Font.BOLD,20));

            g.drawString(message01,530 ,190);
            g.drawString(message02,530 ,220);

            //在背景图片上添加二维码图片
             g.drawImage(qrCode, 700, 240, qrCode.getWidth(), qrCode.getHeight(), null);

            g.dispose();

            //输出图片
            ImageIO.write(background, "jpg", new File(outPutPath));
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     *
     * 图片处理加字列表 InputPath图片路径 outputPath输出路径（为空上传到腾讯云oss 字体设置列表）
     * @return
     */
    public String writeImage(String InputPath,String outputPath,List<FontForm> formList) {
        BufferedImage bufferedImage = cn.sky1998.mango.common.utils.FileUtils.readFileBufferedImage(InputPath);
        BufferedImage background = resizeImage(getImgWidth(InputPath),getImgHeight(InputPath), bufferedImage);
        //在背景图片中添加入需要写入的信息，例如：扫描下方二维码，欢迎大家添加我的淘宝返利机器人，居家必备，省钱购物专属小秘书！
        for (FontForm fontForm : formList) {

            Graphics2D g2 = background.createGraphics();
            g2.setColor(fontForm.getColor());
            g2.setFont(new Font(fontForm.getName(),fontForm.getStyle(),fontForm.getSize()));

            g2.drawString(fontForm.getTitle(),fontForm.getX() ,fontForm.getY());

            g2.dispose();
        }

        //输出图片
        try {
            if (outputPath==null){
                //输出图片
                String tempFileName=IdUtils.fastSimpleUUID() + ".jpg";
                File file = new File(mangoConfig.getTempFile() + tempFileName);
                ImageIO.write(background, "jpg",file);
                String s = fileUtils.uploadTencentOss(new FileInputStream(file), IdUtils.fastSimpleUUID() + ".jpg");
                cn.sky1998.mango.common.utils.FileUtils.deleteFile(mangoConfig.getTempFile() + tempFileName);
                return s;
            }else {
                ImageIO.write(background, "jpg", new File(outputPath));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     *  二维码所处的位置
     * @param backgroundPath 背景图
     * @param qrCodePath 二维码
     * @param message01 文字1
     * @param message02 文字2
     * @return 腾讯云oss 图片地址
     */
    public String overlapImage(String backgroundPath,String qrCodePath,String message01,String message02){
        String s = null;
        try {
            //背景图片处理----------
            URL urlback = new URL(backgroundPath);
            HttpURLConnection connback=(HttpURLConnection)urlback.openConnection();
            //设置超时间为3秒
            connback.setConnectTimeout(3*1000);
            //防止屏蔽程序抓取而返回403错误
            connback.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            InputStream inputStreamBack =connback.getInputStream();

             File fileback = new File(mangoConfig.getProfile()+"/end.png");
             FileUtils.copyInputStreamToFile(inputStreamBack,fileback);

            //二维码处理----start-----
            URL urlcode = new URL(qrCodePath);
            HttpURLConnection conncode=(HttpURLConnection)urlcode.openConnection();
            //设置超时间为3秒
            conncode.setConnectTimeout(3*1000);
            //防止屏蔽程序抓取而返回403错误
            conncode.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            InputStream inputStreamcode =conncode.getInputStream();
            File filecode = new File(mangoConfig.getProfile()+"/code.png");
            FileUtils.copyInputStreamToFile(inputStreamcode,filecode);
            //二维码处理-------------end--------------------
            //设置背景图片大小
            BufferedImage background = resizeImage(1000,618, ImageIO.read(fileback));
            BufferedImage qrCode = resizeImage(150,150,ImageIO.read(filecode));

            //在背景图片中加字---------start--------
            Graphics2D g = background.createGraphics();
            g.setColor(Color.white);
            g.setFont(new Font("微软雅黑",Font.BOLD,20));

            g.drawString(message01,530 ,190);
            g.drawString(message02,530 ,220);
            //在背景图片中加字---------end--------
            //在背景图片上添加二维码图片
            g.drawImage(qrCode, 700, 240, qrCode.getWidth(), qrCode.getHeight(), null);

            g.dispose();

            //输出图片
            ImageIO.write(background, "jpg", new File(mangoConfig.getProfile()+"/end.png"));
             s = fileUtils.uploadTencentOss(new FileInputStream(fileback), IdUtils.fastSimpleUUID() + ".jpg");

        }catch (Exception e){
            e.printStackTrace();
        }
        return s;
    }
    /**
     * 设置图片大小
     * @param x
     * @param y
     * @param bfi
     * @return
     */
    public static BufferedImage resizeImage(int x, int y, BufferedImage bfi){
        BufferedImage bufferedImage = new BufferedImage(x, y, BufferedImage.TYPE_INT_RGB);
        bufferedImage.getGraphics().drawImage(
                bfi.getScaledInstance(x, y, Image.SCALE_SMOOTH), 0, 0, null);
        return bufferedImage;
    }

    /**
     * 获取图片宽度
     * @param imgPath
     * @return
     */
    public static Integer getImgWidth(String imgPath){
        // 文件对象
        File file = new File(imgPath);
        // 文件大小；其中file.length()获取的是字节，除以1024可以得到以kb为单位的文件大小
        long size = file.length() / 1024;
        // 图片对象
        BufferedImage bufferedImage = null;
        try {
            bufferedImage = ImageIO.read(new FileInputStream(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 宽度
        int width = bufferedImage.getWidth();

        return width;
    }

    /**
     * 获取图片高度
     * @param imgPath
     * @return
     */
    public static Integer getImgHeight(String imgPath){
        // 文件对象
        File file = new File(imgPath);
        // 文件大小；其中file.length()获取的是字节，除以1024可以得到以kb为单位的文件大小
        long size = file.length() / 1024;
        // 图片对象
        BufferedImage bufferedImage = null;
        try {
            bufferedImage = ImageIO.read(new FileInputStream(file));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 高度
        int height = bufferedImage.getHeight();

        return height;
    }
}